<?php

namespace app\middleware;

use tinywan\JWT;
use think\exception\ValidateException;
use think\facade\Log;

class JwtAuth
{
    public function handle($request, \Closure $next)
    {
        // 打印请求头信息
        Log::info('JWT Auth Middleware started');
        Log::info('Authorization Header: ' . $request->header('authorization'));

        $token = $request->header("authorization");
        Log::info('Extracted token===================================: ' . $token);
        try {
            // 获取token
            $token = JWT::getTokenFromHeaders();
            Log::info('Extracted token---------------------------------------------------: ' . $token);

            // 验证token
            $payload = JWT::verifyToken($token);
            Log::info('Token verified successfully: ' . json_encode($payload));

            // 将用户信息存入请求
            $request->user = $payload;

            return $next($request);
        } catch (\Exception $e) {
            // 记录异常信息
            Log::error('JWT Exception: ' . $e->getMessage());
            Log::error('Exception Trace: ' . $e->getTraceAsString());

            // 返回未授权响应
            return json([
                'code' => 402,
                'msg' => 'Unauthorized: ' . $e->getMessage(),
                'data' => []
            ], 402);
        }
    }
}